package com.aneliya.client;

import java.io.IOException;
import java.util.Vector;

import com.aneliya.model.Message;
import com.aneliya.model.MessageType;
import com.aneliya.server.dispatcher.Dispatcher;

public abstract class ClientSender extends Thread {
	private Vector<Message> messageQueue = new Vector<Message>();
	
	private IClient client;
	public void setClient(IClient client) {
		this.client = client;
	}
	
	private Dispatcher dispatcher;
	public void setDispatcher(Dispatcher dispatcher) {
		this.dispatcher = dispatcher;
	}
	
	public synchronized void sendMessage(Message message) {
		messageQueue.add(message);
		notify();
	}
	
	public synchronized void sendKeepAlive() {
		Message keepAliveMessage = new Message(null, null);
		keepAliveMessage.setMessageType(MessageType.KEEP_ALIVE);
		sendMessage(keepAliveMessage);
	}
	
	private synchronized Message getNextMessageFromQueue() throws InterruptedException {
		while (messageQueue.size() == 0) {
			wait();
		}
		Message message = messageQueue.firstElement();
		messageQueue.remove(0);
		return message;
	}
	
	protected abstract void sendMessageToClient(Message message) throws IOException;
	
	public void run() {
		try {
			while (!isInterrupted()) {
				Message message = getNextMessageFromQueue();
				sendMessageToClient(message);
			}
		} catch (Exception ex) {
			// Communication problem
		}
		
		client.interruptClientListener();
		dispatcher.removeClient(client);
	}
}
